//
//  OffUpLoadView.m
//  BMW
//
//  Created by up72-2 on 15/10/26.
//  Copyright © 2015年 up72-2. All rights reserved.
//

#import "OffUpLoadView.h"
#import "GWQuestionnaire.h"

@interface OffUpLoadView()
{
    GWQuestionnaire *surveyController;
    
    NSMutableArray *areaArr;
}
@end
@implementation OffUpLoadView

- (void)awakeFromNib
{
    [self handlePlist];
}

- (void)handlePlist
{
    

    [self handleData];
}

- (void)handleData
{
    NSMutableArray *questions = [NSMutableArray array];
    //处理数据
    //获取数据
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"LongSurvey" ofType:@"plist"];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    //添加数据 （第一个）
    GWQuestionnaireItem *item1;
    NSMutableArray *answerArr = [NSMutableArray array];
    //购买意向
    for (int j=0; j<[[dictionary objectForKey:@"100"] allValues].count; j++) {
        NSDictionary *singleDic = [NSDictionary dictionaryWithObjectsAndKeys:[[[dictionary objectForKey:@"100"] allValues] objectAtIndex:j],@"text",[NSNumber numberWithBool:NO],@"marked",[[[dictionary objectForKey:@"100"] allKeys] objectAtIndex:j],@"key", nil];
        [answerArr addObject:singleDic];
    }
    item1 = [[GWQuestionnaireItem alloc]initWithQuestion:@"*  购买意向" answers:answerArr type:GWQuestionnaireSingleChoice];

   
    NSArray *ar =  [[[dictionary objectForKey:@"300"] allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    NSMutableArray *carArr = [NSMutableArray array];
    GWQuestionnaireItem *item2;
    for (int j=0; j<ar.count; j++) {
        NSDictionary *singleDic = [NSDictionary dictionaryWithObjectsAndKeys:[[dictionary objectForKey:@"300"] objectForKey:[ar objectAtIndex:j]],@"text",[NSNumber numberWithBool:NO],@"marked",[ar objectAtIndex:j],@"key", nil];
        [carArr addObject:singleDic];
    }
    
    item2 = [[GWQuestionnaireItem alloc]initWithQuestion:[NSString stringWithFormat:@"%@",@"*  感兴趣的BMW车型 (可多选)"] answers:carArr type:GWQuestionnaireMultipleChoice];
    
    //摩托车
    NSArray *motoAr = [[[dictionary objectForKey:@"200"] allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    NSMutableArray *motoArr = [NSMutableArray array];
    GWQuestionnaireItem *item3;
    for (int j=0; j<motoAr.count; j++) {
        NSDictionary *singleDic = [NSDictionary dictionaryWithObjectsAndKeys:[[dictionary objectForKey:@"200"] objectForKey:[motoAr objectAtIndex:j]],@"text",[NSNumber numberWithBool:NO],@"marked",[motoAr objectAtIndex:j],@"key", nil];
        [motoArr addObject:singleDic];
    }
    item3 = [[GWQuestionnaireItem alloc]initWithQuestion:@"摩托车" answers:motoArr type:GWQuestionnaireMultipleChoice];
    
    [questions addObject:item1];
    [questions addObject:item2];
    [questions addObject:item3];
    
    [surveyController.view removeFromSuperview];
    surveyController = [[GWQuestionnaire alloc] initWithItems:questions];
    surveyController.view.frame = CGRectMake(0,0,self.frame.size.width,self.frame.size.height - 51);
    [self addSubview:surveyController.view];
    
    
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.frame.size.height-51, kScreenWidth, 51)];
    imgV.userInteractionEnabled = YES;
    imgV.image = [UIImage imageNamed:@"bottom"];
    [self addSubview:imgV];
    
    // add button
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTitle:@"提 交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"cancle"] forState:0];
    [btn addTarget:self action:@selector(getAnswersPressed:) forControlEvents:UIControlEventTouchUpInside];
    int btnW = 150;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setFrame:CGRectMake(self.bounds.size.width-btnW, 7, 100, 37)];
    [imgV addSubview:btn];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)getAnswersPressed:(UIButton *)sender
{
    
    if ([surveyController.tableHeader.firstName.text length] <= 0) {
        [MTool showMessage:@"请输入姓" inView:self];
        return;
    }
    if (![IdentifierValidator validateZHandEN:surveyController.tableHeader.firstName.text]) {
        [MTool showMessage:@"姓只能输入中文或英文" inView:self];
        return;
    }
    if ([surveyController.tableHeader.firstName.text length] > 20) {
        [MTool showMessage:@"姓不能超过20个字符" inView:self];
        return;
    }
    
    if ([surveyController.tableHeader.secondName.text length] <= 0) {
        [MTool showMessage:@"请输入名" inView:self];
        return;
    }
    if (![IdentifierValidator validateZHandEN:surveyController.tableHeader.secondName.text]) {
        [MTool showMessage:@"名只能输入中文或英文" inView:self];
        return;
    }
    if ([surveyController.tableHeader.secondName.text length] > 20) {
        [MTool showMessage:@"名不能超过20个字符" inView:self];
        return;
    }
    
    if ([surveyController.tableHeader.provinceBtn.titleLabel.text length] <= 0) {
        [MTool showMessage:@"请选择省份" inView:self];
        return;
    }
    
    if ([surveyController.tableHeader.cityBtn.titleLabel.text length] <= 0) {
        [MTool showMessage:@"请选择城市或区" inView:self];
        return;
    }
    
    if (![IdentifierValidator isValid:IdentifierTypePhone value:surveyController.tableHeader.teleTF.text]) {
        [MTool showMessage:@"请输入正确的手机号" inView:self];
        return;
    }
    
    

    
    
    if(![surveyController isCompleted])
    {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请完成所有问题！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
        [MTool showMessage:@"请完成所有问题！" inView:self];
        return;
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    
    for(GWQuestionnaireItem *item in surveyController.surveyItems)
    {
        if(item.type == GWQuestionnaireOpenQuestion) {
            //文本
            NSLog(@"Answer: %@", item.userAnswer);
            NSDictionary *temp = [item.answers objectAtIndex:0];
//            [dic setObject:item.userAnswer forKey:[temp objectForKey:@"key"]];
            
        } else if(item.type == GWQuestionnaireSingleChoice) {
            //单选
            for(NSDictionary *dict in item.answers)
            {
                NSLog(@"%d - %@ - %@",[[dict objectForKey:@"marked"]boolValue], [dict objectForKey:@"text"],[dict objectForKey:@"key"]);
                if ([[dict objectForKey:@"marked"] boolValue] == YES) {
                    [dic setObject:[dict objectForKey:@"text"] forKey:@"purchaseIntention"];
                }
            }
        }
        else
        {
            //多选
            NSString *keyStr = @"";
            NSMutableArray *arr = [NSMutableArray array];
            for(NSDictionary *dict in item.answers)
            {
                keyStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"key"]];
                NSLog(@"%d - %@ - %@",[[dict objectForKey:@"marked"]boolValue], [dict objectForKey:@"text"],[dict objectForKey:@"key"]);
                if ([[dict objectForKey:@"marked"] boolValue] == YES) {
                    [arr addObject:[dict objectForKey:@"text"]];
                    
                }
            }
            if ([item.question isEqualToString:@"*  感兴趣的BMW车型 (可多选)"]) {
                NSString *valueStr = [arr componentsJoinedByString:@";"];
                [dic setObject:valueStr forKey:@"beInterestedCar"];
            } else {
                NSString *valueStr = [arr componentsJoinedByString:@";"];
                [dic setObject:valueStr forKey:@"motorbike"];
            }
        }
    }
    
    
    
    [dic setObject:surveyController.tableHeader.firstName.text forKey:@"surname"];
    [dic setObject:surveyController.tableHeader.secondName.text forKey:@"fame"];
    if (surveyController.tableHeader.sex == 0) {//男
        [dic setObject:@"男" forKey:@"sex"];
    } else {//女
        [dic setObject:@"女" forKey:@"sex"];
    }
    
    [dic setObject:surveyController.tableHeader.provinceBtn.titleLabel.text forKey:@"province"];
    [dic setObject:surveyController.tableHeader.cityBtn.titleLabel.text forKey:@"city"];
    [dic setObject:surveyController.tableHeader.teleTF.text forKey:@"mobilePhone"];
    
    if (!netManager) {
        netManager = [[NetManager alloc] init];
        [netManager setDelegate:self];
    }
    [netManager setRequestDic:dic];
    netManager.requestId = 100;
    [netManager setLoadingText:@"正在处理中.."];
    [netManager checkSingnature:[dic objectForKey:@"surname"] phone:[dic objectForKey:@"mobilePhone"]];
    
    
}



#pragma mark - 网络请求
- (void)requestStart:(NetManager *)request
{
    
}

- (void)requestError:(NetManager *)request error:(NSError *)error
{
    
}

- (void)requestDidFinished:(NetManager *)request result:(NSMutableDictionary *)result
{
    NSInteger status = [[NSString stringWithFormat:@"%@",[result objectForKey:@"state"]] integerValue];
    
    if (status != 1) {
        [MTool showMessage:[NSString stringWithFormat:@"%@",[result objectForKey:@"errorMsg"]] inView:self];
        return;
    }
    
    if (request.requestId == 100) {
        if ([[[result objectForKey:@"data"] objectForKey:@"existSignature"] integerValue] == 0) {//代表不存在
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showSigmatureView" object:nil userInfo:request.requestDic];
        } else {
            NSLog(@"协议存在");
            netManager.requestId = 200;
            netManager.loadingText = @"信息上传中..";
            [netManager signIn: [NSMutableDictionary dictionaryWithDictionary:request.requestDic]];
        }
    }
    else if (request.requestId == 200)
    {
        [MTool showMessage:@"提交成功" inView:self];
        //清除数据
        
        [self handlePlist];
    }
}


@end
